// 验证IP的正则
var ip_reg =
	/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

// 验证子网掩码的正则
var mask_reg =
	/^(254|252|248|240|224|192|128|0)\.0\.0\.0|255\.(254|252|248|240|224|192|128|0)\.0\.0|255\.255\.(254|252|248|240|224|192|128|0)\.0|255\.255\.255\.(254|252|248|240|224|192|128|0)$/;

/**
 *　　把IP地址转换成二进制格式
 *　　@param string   ip    待转换的IP的地址
 */
function ip_to_binary(ip) {
	if (ip_reg.test(ip)) {
		var ip_str = "",
			ip_arr = ip.split(".");

		for (var i = 0; i < 4; i++) {
			curr_num = ip_arr[i];
			number_bin = parseInt(curr_num);
			number_bin = number_bin.toString(2);
			count = 8 - number_bin.length;
			for (var j = 0; j < count; j++) {
				number_bin = "0" + number_bin;
			}
			ip_str += number_bin;
		}
		return ip_str;
	}

	return '';
}

/**
 *　　把二进制格式转换成IP地址
 *　　@param string   binary    待转换的二进制　　
 */
function binary_to_ip(binary) {
	if (binary.length == 32) {
		a = parseInt(binary.substr(0, 8), 2);
		b = parseInt(binary.substr(8, 8), 2);
		c = parseInt(binary.substr(16, 8), 2);
		d = parseInt(binary.slice(-8), 2);

		return a + '.' + b + '.' + c + '.' + d;
	}

	return '';
}


/**
 *　　根据子网掩码和网关计算网络地址和广播地址
 *　　@param  string    mask    子网掩码
 *　　@param  string    gateway 网关
 */
function get_network_broadcast_addr(mask, gateway) {
	network_broadcast = [];
	network_addr = "";

	mask_arr = mask.split(".");
	ip_arr = gateway.split(".");

	// 计算IP的网络地址 与(&)运算
	for (var i = 0; i < 4; i++) {
		number1 = parseInt(mask_arr[i]);
		number2 = parseInt(ip_arr[i]);
		network_addr += number1 & number2;
		if (i < 3) {
			network_addr += ".";
		}
	}
	network_broadcast.push(network_addr);

	// 计算广播地址
	// 子掩码后面有几个0，就去掉IP地址后几位再补1
	mask_binary = ip_to_binary(mask);
	gateway_binary = ip_to_binary(gateway);

	mask_zero = mask_binary.split(0).length - 1;
	one_number = new Array(mask_zero + 1).join('1'); // IP地址后位补1
	gateway_hou_wei_bu_yi = gateway_binary.slice(0, -mask_zero) + one_number;

	network_broadcast.push(binary_to_ip(gateway_hou_wei_bu_yi));

	return network_broadcast;
}

function int2iP(num) {
	var str;
	var tt = new Array();
	tt[0] = (num >>> 24) >>> 0;
	tt[1] = ((num << 8) >>> 24) >>> 0;
	tt[2] = (num << 16) >>> 24;
	tt[3] = (num << 24) >>> 24;
	str = String(tt[0]) + "." + String(tt[1]) + "." + String(tt[2]) + "." + String(tt[3]);
	return str;
}

function ip2int(ip) {
	var num = 0;
	ip = ip.split(".");
	num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]);
	num = num >>> 0;
	return num;
}

function PingIP() {
	var DatagramSocket = plus.android.importClass("java.net.DatagramSocket");
	var DatagramPacket = plus.android.importClass("java.net.DatagramPacket");
	var InetAddress = plus.android.importClass("java.net.InetAddress");
	var StrictMode = plus.android.importClass("android.os.StrictMode");
	var Build = plus.android.importClass("android.os.Build");
	if (Build.VERSION.SDK_INT > 9) {
		var policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
		StrictMode.setThreadPolicy(policy);
	}
	var data = new Array(0x82, 0x28, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x20, 0x43, 0x4B, 0x41, 0x41,
		0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
		0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x0, 0x0, 0x21, 0x0, 0x1);
	var nobj = GetNetworkObj();
	var addr = get_network_broadcast_addr(nobj.netmask, nobj.gateway)
	//console.log(addr[0])
	//console.log(addr[1])
	var j = 0;
	for (var i = ip2int(addr[0]) + 1; i < ip2int(addr[1]); i++) {
		//console.log(int2iP(i))
		j++;
		if (j > 255) {
			break;
		}
		var udp = new DatagramSocket();
		var packet = new DatagramPacket(data, data.length, InetAddress.getByName(int2iP(i)), 137);
		udp.send(packet);
		udp.close();
	}
	ReadArp();
}
//读取ARP文件
function ReadArp() {
	plus.io.resolveLocalFileSystemURL("/proc/net/arp", function(entry) {
		// 可通过entry对象操作test.html文件 
		entry.file(function(file) {
			var fileReader = new plus.io.FileReader();
			fileReader.readAsText(file, 'utf-8');
			fileReader.onloadend = function(evt) {
				//console.log("11" + evt);
				//console.log("evt.target" + evt.target);
				//console.log(evt.target.result);
				var listt = evt.target.result.split(/[\r\n]/)
				OnLivePC = new Array();
				for (var i = 0; i < listt.length; i++) {
					var t = listt[i]
					if (t.indexOf("00:00:00:00:00:00") == -1 && t.indexOf("IP") == -1) {
						if (isValidIP(t)) {
							//console.log(t)
							var tempPc = {
								ip: GetIPFromStr(t),
								mac: GetMacFromStr(t.toUpperCase())
							};
							OnLivePC.push(tempPc);
						}
					}
				}

				//console.log(JSON.stringify(OnLivePC))
				var ul = $("#onLives").html("");
				if (OnLivePC.length == 0) {
					ul.append($("<center>").text("没有在线设备"));
				}
				for (var i = 0; i < OnLivePC.length; i++) {
					var ip = OnLivePC[i].ip;
					var mac = OnLivePC[i].mac + '';
					mac = mac.replace(/:/g, "-");
					var li = $("<li>").text(ip + "(" + mac + ")")
					li.on("click", {
						ip: ip,
						mac: mac
					}, function(e) {
						$("#pcip").val(e.data.ip);
						$("#pcmac").val(e.data.mac);
					});
					ul.append($("<center>").append(li));
				}

			}
		});
	}, function(e) {});
}


function GetMacFromStr(ip) {
	var reg = /[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}:[A-F\d]{2}/;
	return ip.match(reg);
}

function GetIPFromStr(ip) {
	var reg =
		/(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)/
	return ip.match(reg)[0];
}

function isValidIP(ip) {
	var reg =
		/(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)\.(2[0-4]\d|25[0-5]|[01]\d\d|\d\d|\d)/
	return reg.test(ip);
}

function IsPCLive(mac) {
	for (var i = 0; i < OnLivePC.length; i++) {
		if (OnLivePC[i].mac == mac.toUpperCase().replace(/-/g, ":")) {
			return true;
		}
	}
	return false;
}


//------------------------------------------------------------------------------
function WIFI() {
	var Context = plus.android.importClass("android.content.Context");
	var WifiManager = plus.android.importClass("android.net.wifi.WifiManager");
	wifiManager = plus.android.runtimeMainActivity().getSystemService(Context.WIFI_SERVICE);
	console.log(wifiManager.isWifiEnabled())
	//wifiManager.setWifiEnabled(false);
	//wifiManager.setWifiEnabled(true);
}

//----------------------------------------
function GetNetworkObj() {
	var wifiManager, wifiInfo;
	var Context = plus.android.importClass("android.content.Context");
	var WifiManager = plus.android.importClass("android.net.wifi.WifiManager");
	var WifiInfo = plus.android.importClass("android.net.wifi.WifiInfo");
	wifiManager = plus.android.runtimeMainActivity().getSystemService(Context.WIFI_SERVICE);
	wifiInfo = wifiManager.getConnectionInfo();
	dhcpInfo = wifiManager.getDhcpInfo();
	//console.log(wifiInfo.getIpAddress())
	//console.log(wifiInfo)
	//console.log(IntToIp(wifiInfo.getIpAddress()))
	//console.log(wifiInfo.getMacAddress())
	//var str1 = DhcpInfoToObj(dhcpInfo);
	//console.log(str1.netmask)
	//console.log(JSON.stringify(DhcpInfoToObj(dhcpInfo)))
	//var wifiObj={di[0]:di[1]};
	//wifiObj.ip=IntToIp(wifiInfo.getIpAddress());
	return DhcpInfoToObj(dhcpInfo)
}

function DhcpInfoToObj(dhcpInfo) {
	var dhcpArry = dhcpInfo.toString().replace("DHCP server", "DHCPserver").replace(" seconds", "seconds").split(" ");
	var dhcpStr = "{"
	dhcpStr += '"' + dhcpArry[0] + '":"' + dhcpArry[1] + '"';
	for (var i = 1; i < dhcpArry.length / 2; i++) {
		var it = 2 * i;
		dhcpStr += ',"' + dhcpArry[it] + '":"' + dhcpArry[it + 1] + '"'
	}
	dhcpStr += "}"
	return JSON.parse(dhcpStr);
}
